package com.itheima.aspect;

import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.OperateLog;
import com.itheima.util.CurrentHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Component
@Slf4j
@Aspect
//@Order(1)
public class LogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(com.itheima.anno.LogOperation)")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        long start = System.currentTimeMillis();
        Object proceed = pjp.proceed();
        long end = System.currentTimeMillis();
        OperateLog operateLog = new OperateLog();
        operateLog.setOperateEmpId(findEmpId());
        operateLog.setOperateTime(LocalDateTime.now());
        String className = pjp.getTarget().getClass().getName();
        operateLog.setClassName(className);
        String methodName = pjp.getSignature().getName();
        operateLog.setMethodName(methodName);
        operateLog.setMethodParams(Arrays.toString(pjp.getArgs()));
        operateLog.setReturnValue(proceed.toString());
        operateLog.setCostTime(end - start);
        operateLogMapper.insert(operateLog);
        log.info("{}.{}方法耗时{}ms", className, methodName, end - start);
        return proceed;
    }

    private int findEmpId() {
        return CurrentHolder.getCurrentId();
    }


}
